import { WereWolfIDDb } from "@/werewolf/module";
import { WereWolfPlayer } from "@/werewolf/player";
import { WereWolfNoColorText } from "@/werewolf/static";
import { world } from "@minecraft/server";
import { PlayerGroup } from "@sapi-game/gamePlayer/playerGroup";
import { GameComponent, TeamScoreBoard } from "@sapi-game/main";
import { WereWolfPickNumberState } from "./state";

interface NoPickerOptions {
    players: PlayerGroup<WereWolfPlayer>;
}

export class WereWolfNoPicker extends GameComponent<
    WereWolfPickNumberState,
    NoPickerOptions
> {
    private readonly PICKER_ID_PREFIX = "werewolf:picker";

    get players() {
        return this.options!.players;
    }

    override onAttach(): void {
        if (!this.options?.players) return;

        this.subscribe(world.afterEvents.itemUse, (t) => {
            if (!t.itemStack.typeId.startsWith(this.PICKER_ID_PREFIX)) return;
            const sel = this.extractSel(t.itemStack.typeId);
            if (!sel) return;
            //获取player(不存在就加)
            const player =
                this.players.getById(t.source.id) ??
                this.state.playerManager.get(t.source);
            if (!this.players.has(player)) this.players.add(player);
            //获取已有玩家，否则添加
            this.handlePick(player, sel);
        });
    }

    handlePick(player: WereWolfPlayer, sel: number) {
        if (!player.isValid) return;

        const takenPlayer = this.players.find((p) => p.no === sel);
        if (takenPlayer) {
            if (takenPlayer == player) {
                return player.sendMessage(`你已经选择了${sel}号`);
            }
            if (this.context.config.restrictMode) {
                return player.sendMessage(`§e${sel}§r号已被其它玩家选择`);
            } else {
                //抢占
                if (takenPlayer.player) WereWolfIDDb.rm(takenPlayer.player);
                takenPlayer.no = 0;
            }
        }
        //设置自己
        player.no = sel;
        this.state.getComponent(TeamScoreBoard).refreshScoreBoard();
        //消息提示
        this.context.map.watingRegion.forEachPlayer((pp) =>
            pp.sendMessage(
                `[${player.name}] 选择了${sel}号 ${
                    WereWolfNoColorText[sel - 1] ?? ""
                }`
            )
        );
        player.player?.playSound("note.bell");
    }

    /**从typeId提取选择的号数 */
    extractSel(typeId: string): number | null {
        const match = typeId.match(/\d+$/);
        return match ? Number(match[0]) : null;
    }
}
